<?php
class ProfilesController extends AppController{
    var $name='Profiles';
    var $uses=array('Profilefield','UserProfile','ProfileFieldValue');
    
    
    
    
    function beforeFilter() {
        parent::beforeFilter();
       // echo $this->Session->setFlash("Welcome user");
        $this->Auth->autoRedirect = false;
        $this->Auth->allow('edit_profile', 'check_email', 'register', 'check_login', 'ajax_register', 'reload_captcha','confirm','successful');
        $this->Auth->loginRedirect = array('controller' => 'Homes', 'action' => 'index');
    }
    
    
    
    function profile_edit(){
        /*query for fetch profile fields*/
        $profilefield=$this->Profilefield->find('all',array('conditions'=>array('status'=>'1'),'order'=>'order ASC'));
        $this->set('profilefield',$profilefield);
        /*profile field end*/
         if(isset($_SESSION['Auth']['user']['User']['id'])){
             $user_id=$_SESSION['Auth']['user']['User']['id'];
             
             $userprofile=$this->ProfileFieldValue->find('all',array('conditions'=>array('ProfileFieldValue.user_id'=>$user_id)));
             $this->set('profilefield1',$userprofile);
              
             $userdetails=$this->UserProfile->find('first',array('conditions'=>array('user_id'=>$user_id)));
             $this->set('profile',$userdetails);
         }
         
         if(!empty($this->data)){
             //debug($this->data);
         }
    }
    
    function profile(){
        
        if(isset($_SESSION['Auth']['user']['User']['id'])){
            $user_id=$_SESSION['Auth']['user']['User']['id'];
            $userdetails=$this->UserProfile->find('first',array('conditions'=>array('UserProfile.user_id'=>$user_id)));
            $this->set('userdetails',$userdetails);
            $this->set('rank',$this->get_user_ranking());
        }
        
    }
    
    function get_user_ranking(){
        
            $get_credits=mysql_query("SELECT SUM(`credit`) as points ,`user_id`FROM `user_credits` GROUP BY `user_id` ORDER BY points DESC");
            $users=array();
            $rank=array();
            $i='0';
            while($row=  mysql_fetch_assoc($get_credits)){
                $users[$i]['id']=$row['user_id'];
                $users[$i]['points']=$row['points'];
                $i++;
            }
            //debug($users);
            
            $uids=Set::classicExtract($users,'{n}.id');
           
            $position=array_search( $_SESSION['Auth']['user']['User']['id'],$uids);
            if($position){
                $rank['rank']=$position+1;
                $rank['points']=$users[$position]['points'];
            }else{ $rank['rank']=count($uids)+1; }

            
            return $rank;
            }



    
    
}
?>
